<script setup>
import { ElMessage } from 'element-plus';
import Layer from "@/components/layer/index.vue";
import { defineProps, ref, defineEmits } from 'vue'
import { addAPI, updateAPI } from '@/api/wedding/productCategory'
import { MessagePlugin } from 'tdesign-vue-next';
import { upload } from '@/api/wedding/attachInfo'


// 使用defineEmits来接收来自父组件的方法
const emit = defineEmits(['getTableData'])
// 声明props
const props = defineProps({
  layer: {
    type: Object,
    default: () => {
      return {
        show: false,
        title: '',
        showButton: true
      }
    }
  }
});

/************************************定义变量************************************************/
const ruleForm = ref(null)
const layerDom = ref(null)
const rules = {
  category: [{ required: true, message: '请输入商品类别', trigger: 'blur' }],
}
let form = ref({
  id: null,
  category: null,
  creator: null,
  createTime: null,
  updateTime: null,
  delFlag: null,
  icon: null,
})

/************************************数据回显************************************************/
if (props.layer.row) {
  if (props.layer.row) {
    let source = props.layer.row
    Object.keys(form.value).forEach(k => k in source && (form.value[k] = source[k]));
  }
}
/************************************上传图片************************************************/
const formLoading = ref(false);
const files = ref([]);
const beforeUpload = (file) => {
  formLoading.value = true;
  if (file.size > 5 * 1024 * 1024) {
    MessagePlugin.warning('上传的图片不能大于5M');
    return false;
  }
  return true;
};
const requestMethod = async (file) => {
  console.log('[ file ] >', file)
  form.file = file.raw;
  form.value.attachName = file.raw.name;
  form.value.fileType = file.raw.type;
  console.log('[ form1 ] >', form)
  try {
    const res = await upload(form);
    if (res.code === 0) {
      form.value.icon = res.data;
      console.log('[ icon ] >', form.icon)
      console.log('[ form2 ] >', form)
      MessagePlugin.success('上传成功');
      formLoading.value = false;
      return new Promise((resolve) => {
        resolve({ status: 'success', response: { url: form.icon } });
      });
    }
    MessagePlugin.success(`上传失败:${res.msg}`);
    return new Promise((resolve) => {
      resolve({ status: 'fail', error: '上传失败' });
    });
  } catch (er) {
    MessagePlugin.success(`上传失败:${er}`);
    return new Promise((resolve) => {
      // resolve 参数为关键代码
      resolve({ status: 'fail', error: '上传失败' });
    });
  }
};
/************************************定义事件************************************************/
//提交按钮事件
let submit = () => {
  if (ruleForm) {
    ruleForm.value.validate((valid) => {
      if (valid) {
        let params = form.value
        if (props.layer.row) {
          updateForm(params)
        } else {
          addForm(params)
        }
      } else {
        return false;
      }
    });
  }
}

let updateForm = (params) => {
  updateAPI(params)
    .then(res => {
      ElMessage({
        type: 'success',
        message: '编辑成功'
      })
      emit('getTableData', false)
      layerDom && layerDom.value.close()
    })
}

let addForm = (params) => {
  addAPI(params)
    .then(res => {
      ElMessage({
        type: 'success',
        message: '新增成功'
      })
      emit('getTableData', true)
      layerDom && layerDom.value.close()
    })
}
</script>

<template>
  <Layer :layer="layer" @confirm="submit" ref="layerDom">
    <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px" style="margin-right:30px;">
      <el-form-item label="商品类别" prop="category">
        <el-input v-model="form.category" placeholder="请输入商品类别" />
      </el-form-item>
      <el-form-item label="上传图片：" prop="fileName">
        <t-image v-if="form.icon" :src="form.icon" mode="aspectFill" width="72" height="72" aria-label="图片" />
        <t-upload v-model="files" :tips="'上传文件大小在 5M 以内'" theme="custom" :before-upload="beforeUpload"
          :request-method="requestMethod">
          <t-button theme="default" variant="outline" :style="{ marginTop: '10px' }">
            <template #icon> <t-icon name="photo"></t-icon> </template>上传图片</t-button>
        </t-upload>
      </el-form-item>
    </el-form>
  </Layer>
</template>

<style scoped lang="scss">
.el-input-number--large {
  line-height: 38px;
  width: 230px;
}
</style>